package com.android.project.sharingdata;

import java.util.HashMap;

import com.android.project.sharingdata.SharedInformation.Sharing;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;

public class ShareDataProvider extends ContentProvider{
	
	private static final String CONTENT_TABLE_NAME = "sharing_table";
	public static final String CONTENT_PROVIDER_DB_NAME = "shareData.db";
	public static final int CONTENT_PROVIDER_DB_VERSION = 1;
//	public static final String CONTENT_PROVIDER_MIME = "vnd.android.cursor.item/vnd.com.android.sharingdata.provider.sharing";
	
	private static final int SHARING_ID = 1;
	private static final int SHARE = 2;
	private static final int CLIENT = 3;
	private static final int DATE = 4;
	
	private static final UriMatcher sUriMatcher;
	
    private static HashMap<String, String> sShareProjectionMap;
	
	private static class DBOpenHelper extends SQLiteOpenHelper {
		
		private static final String CREATE_BDD = "CREATE TABLE "
				+ ShareDataProvider.CONTENT_TABLE_NAME + " ("
				+ Sharing.SHARING_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ Sharing.SHARE + " TEXT NOT NULL,"
				+ Sharing.CLIENT + " TEXT NOT NULL,"
				+ Sharing.DATE + " LONG" + ");";
		
		public DBOpenHelper(Context context) {
			super(context, ShareDataProvider.CONTENT_PROVIDER_DB_NAME, null, ShareDataProvider.CONTENT_PROVIDER_DB_VERSION);
			Log.i("test : Constructeur", "je suis passer dans le constructeur de la base");
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.i("test : oncreate", "je suis passer dans le onCreate de la bdd");
			db.execSQL(CREATE_BDD);
			Log.i("test : apres l'exec", "........");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.i("test : upgrade", "je suis dans le upgrade");
			db.execSQL("DROP TABLE IF EXISTS "+ ShareDataProvider.CONTENT_TABLE_NAME);
			onCreate(db);	
		}
	}
	
	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(SharedInformation.AUTHORITY, "share", SHARE);
		sUriMatcher.addURI(SharedInformation.AUTHORITY, "sharing/#", SHARING_ID);
		sUriMatcher.addURI(SharedInformation.AUTHORITY, "client", CLIENT);
		sUriMatcher.addURI(SharedInformation.AUTHORITY, "sharing/#/date", DATE);
		
        sShareProjectionMap = new HashMap<String, String>();
        sShareProjectionMap.put(Sharing.SHARING_ID, Sharing.SHARING_ID);
        sShareProjectionMap.put(Sharing.SHARE, Sharing.SHARE);
        sShareProjectionMap.put(Sharing.CLIENT, Sharing.CLIENT);
        sShareProjectionMap.put(Sharing.DATE, Sharing.DATE);
	}
	
	private DBOpenHelper dbOpenHelper;
	
	@Override
	public boolean onCreate() {
		Log.i("test : oncreate", "je suis passer dans le onCreate boolean");
		dbOpenHelper = new DBOpenHelper(getContext());
		Log.i("test : base", dbOpenHelper.toString());
		return true;
	}
	
	
	
	@Override
	public String getType(Uri uri) {
		 switch (sUriMatcher.match(uri)) {
	        case SHARE:
	        	
	        case SHARING_ID:
	            return Sharing.CONTENT_ITEM_TYPE;

	        case CLIENT:
	            return Sharing.CONTENT_ITEM_TYPE;
	            
	        case DATE:
	            return Sharing.CONTENT_ITEM_TYPE;

	        default:
	            throw new IllegalArgumentException("Unknown URI get type" + uri);
	     }
	}

	@SuppressWarnings("unused")
	private long getId(Uri uri) {
		String lastPathSegment = uri.getLastPathSegment();
		if (lastPathSegment != null) {
			try {
				return Long.parseLong(lastPathSegment);
			} catch (NumberFormatException e) {
				Log.e("ShareDaTaProvider", "Number Format Exception : " + e);
			}
		}
		return -1;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		Log.i("test : Insert", "debut de l'insert");
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		Log.i("test : Insert", "avant le try insert");
		try {
			Log.i("test : Insert", "dans le try insert");
			long id = db.insertOrThrow(
					ShareDataProvider.CONTENT_TABLE_NAME, null,values);
			
			if (id == -1) {
				
				throw new RuntimeException(String.format(
						"%s : Failed to insert [%s] for unknown reasons.",
						"ShareDataProvider", values, uri));
			} else {
				Log.i("test : Insert", "return insert");
				return ContentUris.withAppendedId(uri, id);
			}

		} finally {
			db.close();
		}
	}
	
//    @Override
//    public Uri insert(Uri uri, ContentValues initialValues) {
//        // Validate the requested uri
//    	Log.i("test : Insert", "je suis dans le insert");
//        if (sUriMatcher.match(uri) != SHARE) {
//            throw new IllegalArgumentException("Unknown URI " + uri);
//        }
//        
//        ContentValues values;
//        if (initialValues != null) {
//            values = new ContentValues(initialValues);
//        } else {
//            values = new ContentValues();
//        }
//
//        Long now = Long.valueOf(System.currentTimeMillis());
//
//        // Make sure that the fields are all set
//        if (values.containsKey(Sharing.DATE) == false) {
//            values.put(Sharing.DATE, now);
//        }
//
//        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
//        long rowId = db.insert(ShareDataProvider.CONTENT_TABLE_NAME, Sharing.SHARE, values);
//        if (rowId > 0) {
//            Uri shareUri = ContentUris.withAppendedId(Sharing.CONTENT_URI, rowId);
//            getContext().getContentResolver().notifyChange(shareUri, null);
//            return shareUri;
//        }
//
//        throw new SQLException("Failed to insert row into " + uri);
//    }

//	@Override
//	public int update(Uri uri, ContentValues values, String selection,
//			String[] selectionArgs) {
//		long id = getId(uri);
//		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
//
//		try {
//			if (id < 0)
//				return db.update(Sharing.TABLE_NAME,
//						values, selection, selectionArgs);
//			else
//				return db.update(
//						Sharing.TABLE_NAME,
//						values, Sharing.SHARING_ID + "=" + id, null);
//		} 
//		finally {
//			db.close();
//		}
//	}
    
    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    	Log.i("test : update", "je suis dans le update de la classe principale");
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case SHARE:
            count = db.update(ShareDataProvider.CONTENT_TABLE_NAME, values, where, whereArgs);
            break;

        case SHARING_ID:
            String shareID = uri.getPathSegments().get(1);
            count = db.update(Sharing.SHARING_ID, values, Sharing.SHARING_ID + "=" + shareID
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI update" + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
	
//	@Override
//	public int delete(Uri uri, String selection, String[] selectionArgs) {
//		long id = getId(uri);
//		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
//		try {
//			if (id < 0)
//				return db.delete(
//						Sharing.TABLE_NAME,
//						selection, selectionArgs);
//			else
//				return db.delete(
//						Sharing.TABLE_NAME,
//						Sharing.SHARING_ID + "=" + id, selectionArgs);
//		} finally {
//			db.close();
//		}
//	}
	
    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
    	Log.i("test : delete", "je suis dans le delete");
        SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case SHARE:
            count = db.delete(ShareDataProvider.CONTENT_TABLE_NAME, where, whereArgs);
            break;

        case SHARING_ID:
            String shareID = uri.getPathSegments().get(1);
            count = db.delete(ShareDataProvider.CONTENT_TABLE_NAME, Sharing.SHARING_ID+ "=" + shareID
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI delete" + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
	

    
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		
		switch (sUriMatcher.match(uri)) {
		case SHARE:
			qb.
			break;
			
		case SHARING_ID:
			break;
			
		case CLIENT:
			break;
			
		case DATE:
			break;
		
		default:
			throw new IllegalArgumentException("Unknow URI query perso" + uri);
		}
		
//		Get the database and run the query
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
	    Log.i("test : avant le curseur", "je suis avant le curseur");
	    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, null);
	    Log.i("test : apres le curseur", "je suis apres le curseur");
	
	      // Tell the cursor what uri to watch, so it knows when its source data changes
	      c.setNotificationUri(getContext().getContentResolver(), uri);
	      return c;
	}
    
//    @Override
//    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
//    	Log.i("test : debut query", "je suis dans le query");
//    	SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
//    	
//        qb.setTables(ShareDataProvider.CONTENT_TABLE_NAME);
//        Log.i("test : query apres ouverture", "je suis apres l'ouverture de la base");
//        
//        switch (sUriMatcher.match(uri)) {
//        case SHARE:
//            qb.setProjectionMap(sShareProjectionMap);
//            Log.i("test : case share query", "je suis dans le case share");
//            break;
//
//        case SHARING_ID:
//            qb.setProjectionMap(sShareProjectionMap);
//            qb.appendWhere(Sharing.SHARING_ID+ "=" + uri.getPathSegments().get(1));
//            Log.i("test : case share_id query", "je suis dans le case share_id");
//            break;
//        
//        case CLIENT:
//        	qb.setProjectionMap(sShareProjectionMap);
//        	Log.i("test : case Client query", "je suis dans le case client");
//        	break;
//        	
//        case DATE:
//        	qb.setProjectionMap(sShareProjectionMap);
//        	Log.i("test : case Date query", "je suis dans le case Date");
//        	break;
//        	
//        default:
//            throw new IllegalArgumentException("Unknown URI query " + uri);
//        }
//        
//        // Get the database and run the query
//        SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
//        Log.i("test : avant le curseur", "je suis avant le curseur");
//        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, null);
//        Log.i("test : apres le curseur", "je suis apres le curseur");
//
//        // Tell the cursor what uri to watch, so it knows when its source data changes
//        c.setNotificationUri(getContext().getContentResolver(), uri);
//        return c;
//    }
    
//	@Override
//	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
//		long id = getId(uri);
//		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
//		if (id < 0) {
//			return db.query(ShareDataProvider.CONTENT_TABLE_NAME,
//							projection, selection, selectionArgs, null, null,
//							sortOrder);
//		} else {
//			return db.query(ShareDataProvider.CONTENT_TABLE_NAME,
//					projection, Sharing.SHARING_ID + "=" + id, null, null, null,
//					null);
//		}
//	}
}
